import { Modal } from 'antd-mobile'
const alert = Modal.alert

function timeout(ms, promise) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      reject(new Error("接口连接超时"))
    }, ms)
    promise.then(resolve, reject)
  })
}

function postUrl(url, params, complete, success, failure){
  console.log(`post ${url} with ${JSON.stringify(params)}`)
  timeout(20000, fetch(url, {
    method: 'POST',
    headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', },
    body: JSON.stringify(params),
  })).then((response) => {
    complete && complete(response)
    return response.json()
  }).then((json) => {
    console.log('resp is', json)
    if (json['status'] == 200) {
      success && success(json['data'])
    } else {
      if(failure == undefined) {
        alert(json['message'])
      } else {
        failure(json)
      }
    }
  }).catch((err) => {
    console.log(err)
    complete && complete()
    alert('提示', err.message)
  })
}

export default {
  post: postUrl
}
